<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-row class="search-row" type="flex" justify="space-between">
      <el-col :span="12">
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item>
            <el-input v-model="keyWord" placeholder="用户名" style="width: 400px;" @keyup.enter="fetchData()"/>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="12">
        <el-button type="primary" @click="fetchData()">
          查询
        </el-button>
        <el-button type="default" @click="resetData()">
          清空
        </el-button>
      </el-col>
    </el-row>

    <!-- 工具条 -->
    <div>
      <el-button v-if="userinfo&& userinfo.yhlx == 1" type="success" size="mini" @click="addUser()" v-permission="'user.add'">
        添加公司管理员
      </el-button>
      <el-button v-if="userinfo&&userinfo.yhlx == 2" type="success" size="mini" @click="addUser()" v-permission="'user.add'">
        添加公司员工
      </el-button>
      <el-button :disabled="multipleSelection.length === 0" type="danger" size="mini" @click="removeRows()"
        v-permission="'user.remove'">
        批量删除
      </el-button>
    </div>

    <!-- 系统用户列表 -->
    <el-table v-loading="listLoading" :data="list" border stripe style="width: 100%" @selection-change="handleSelectionChange"
      :highlight-current-row="true">
      <el-table-column type="selection" width="55" />

      <el-table-column label="序号" width="70" align="center">
        <template #default="{ $index }">
          {{ (page - 1) * limit + $index + 1 }}
        </template>
      </el-table-column>

      <el-table-column prop="yhm" label="用户名" width="150" align="center" />
      <el-table-column prop="js" label="角色" width="200" align="center">
        <template #default="scope">
          <el-tag v-if="scope.row.rylx != null && scope.row.rylx != ''" v-for="item in scope.row.rylx.split('|')">
            {{ item }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="gsmc" label="公司名称" width="100" align="center" />

      <!-- <el-table-column prop="gmtCreate" label="创建时间" width="180"/> -->

      <el-table-column label="操作" width="400" align="center" fixed="right">
        <template #default="{ row }">
          <div class="operation-buttons">
            <el-button v-if="(userinfo&&userinfo.yhlx === 1 && row.yhlx == 2) || (userinfo&&userinfo.yhlx === 2 && row.yhlx == 3)"
                type="info"  v-permission="'user.assgin'"  @click="$router.push('/acl/user/role/' + row.id)" plain>
                分配角色
              </el-button>
              <el-button type="primary"  v-permission="'user.update'" @click="$router.push('/acl/user/update/' + row.id)"  plain>
                用户修改
              </el-button>
            <el-button type="info"  @click="resetPwd(row.id)"  plain>
              重置密码
            </el-button>
            <el-button type="danger"  @click="removeDataById(row.id)" v-permission="'user.remove'"
              plain>
              删除
            </el-button>

          </div>

        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination :background="true" :current-page="page" :total="total" :page-size="limit"
      :page-sizes="[5, 10, 20, 30, 40, 50, 100]" style="padding: 30px 0; text-align: center"
      layout="total, sizes, prev, pager, next, jumper" @current-change="fetchData" @size-change="changeSize" />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import userApi from '@/api/acl/user'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
// import { useUserinfo } from '@/components/Avatar/hooks/useUserinfo'
import { useAccount } from '@/pinia/modules/account'
import { storeToRefs } from 'pinia'

// const { userinfo } = useUserinfo()
const { userinfo } = storeToRefs(useAccount())

interface User {
  id: number
  gh: string
  yhm: string
  js: string
  rylx: string
  gsmc: string
}

const listLoading = ref<boolean>(true)
const list = ref<User[] | null>(null)
const total = ref<number>(0)
const page = ref<number>(1)
const limit = ref<number>(10)
const keyWord = ref<string>('')
const multipleSelection = ref<User[]>([])
const router = useRouter()

/**
 * 重置密码
 */
const resetPwd = (id) => {
  let idList = [id]
  userApi.resetUserPwd(idList).then(() => {
    ElMessage({
      type: 'success',
      message: '重置密码成功',
    })
    fetchData(page.value)
  })
}


const addUser = () => {
  router.push({ path: '/acl/user/add' })
}

const fetchData = (toPage: number = 1) => {
  listLoading.value = true
  userApi
    .getPageList({
      page: toPage,
      limit: limit.value,
      keyWord: keyWord.value.trim(),
    })
    .then(res => {
      list.value = res.data.list
      total.value = res.data.totalCount
      listLoading.value = false
      page.value = toPage
    })
}

const resetData = () => {
  keyWord.value = ''
  fetchData()
}

const removeDataById = (id: string) => {
  ElMessageBox.confirm('确定删除选中的记录吗?', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      var idList = []
      idList.push(id)
      userApi
        .removeRows(idList)
        .then(() => {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          fetchData(page.value)
        })
        .catch(error => {
          console.log(error)
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      })
    })
}

const handleSelectionChange = (selection: User[]) => {
  multipleSelection.value = selection
}

const removeRows = () => {
  ElMessageBox.confirm('确定删除选中的记录吗?', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      var idList = []
      multipleSelection.value.forEach(item => idList.push(item.id))
      userApi
        .removeRows(idList)
        .then(() => {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          fetchData(page.value)
        })
        .catch(error => {
          console.log(error)
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      })
    })
}

const changeSize = (size: number) => {
  limit.value = size
  fetchData(1)
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.operation-buttons {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.button-link {
  text-decoration: none;
}

.assign-role-btn,
.edit-user-btn,
.reset-pwd-btn,
.delete-user-btn {
  margin-right: 10px;
  /* 根据需要调整按钮之间的间距 */
}

.assign-role-btn,
.edit-user-btn,
.reset-pwd-btn,
.delete-user-btn:last-child {
  /* color: var(--primary-color); */
  color: white;
  /* 使用主题色，或自定义颜色 */
  margin-right: 0;
}
</style>